package com.liyong.pullorder.channels.parse;

import com.liyong.pullorder.channels.dto.StandardOrderDto;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class XmlParserStrategy implements ParserStrategy {
    @Override
    public String getFormat() { return "XML"; }

    @Override
    public List<StandardOrderDto> parse(String input, Map<String, String> fieldMapping) {
        List<StandardOrderDto> list = new ArrayList<>();
        try {
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(new org.xml.sax.InputSource(new java.io.StringReader(input)));
            NodeList orders = doc.getElementsByTagName(fieldMapping.getOrDefault("itemTag", "order"));
            for (int i = 0; i < orders.getLength(); i++) {
                org.w3c.dom.Element el = (org.w3c.dom.Element) orders.item(i);
                StandardOrderDto dto = new StandardOrderDto();
                dto.setOrderId(el.getElementsByTagName(fieldMapping.getOrDefault("orderId", "orderId")).item(0).getTextContent());
                dto.setStatus(el.getElementsByTagName(fieldMapping.getOrDefault("status", "status")).item(0).getTextContent());
                String amt = el.getElementsByTagName(fieldMapping.getOrDefault("amount", "amount")).item(0).getTextContent();
                dto.setAmount(amt == null ? null : new java.math.BigDecimal(amt));
                dto.setCreatedAt(el.getElementsByTagName(fieldMapping.getOrDefault("createdAt", "createdAt")).item(0).getTextContent());
                list.add(dto);
            }
        } catch (Exception e) {
            throw new RuntimeException("XML parse error: " + e.getMessage(), e);
        }
        return list;
    }
}